/**
 * 代理中心
 * @author sherwyn.Tang
 * @create 2015/03/07
 */
;(function (global){
	var CGI = {
		PROXY_PAGING: window.frontPath + 'proxy/pagingProxy',	//查询会员 上下级
		PROXY_ADD_VIP: window.frontPath + 'proxy/saveProxy',	//保存会员数据
		NEXT_LEVEL_VIP : window.frontPath + 'proxy/pagingSubagent',	//查询下级代理
		CUR_PROXY_INFO : function (){return window.frontPath + 'proxy/curProxyInfo?r=' + new Date().getTime();},	//查询单个会员
		UPDATE_SUB_VIP : function (){return window.frontPath + 'proxy/updateSubProxy?r=' + new Date().getTime();},		//提交修改
		CHARGE_SUB_PROXY : function (){return window.frontPath + 'proxy/chargeSubProxy?r=' + new Date().getTime();}//给下级会员充值 接口
	};
	
	var ADD_VIP_ERROR = {
		LOGIN_NAME 	: {
			ERROR : '用户名格式错误'
		},
		USER_PWD  	: {
			NULL  : '密码不能为空',
			ERROR : '密码格式错误'
		},
		CONF_PWD 	: {
			NULL  : '确认密码不能为空',
			ERROR : '确认密码跟密码不一致'
		},
		QQ 			: {
			ERROR : 'QQ号格式不对'
		},
		USER_NAME 	: {
			NULL  : '姓名不能为空',
			ERROR : '姓名必须为8个字符以下'
		},
		FANDIAN  	: {
			ERROR : '返点格式不对，必须是>=0 并且是 <={maxFandian} 的点'
		}
	};
	//初始化输入框默认提示组件
	$.placeholder.init();

	/**
	 * 按条件查询
	 */
	$('#proxy-vip-search').click(function (){
		window.Pager.data = null;
		window.P(
			1,
			'#proxy-search-form' , 
			 CGI.PROXY_PAGING , 
			'#proxy-z-template' , 
			'#proxy-data' , 
			15
		);
	}).trigger('click');
	$('#proxy-data').delegate('[data-flag="next-level"]' , 'click' , function (){
		var _uid = $(this).parents('tr').attr('data-uid');
		window.Pager.data = 'userName=&userRelation=4&uid='+_uid;
		window.P(
			1,
			'#proxy-search-form' , 
			 CGI.NEXT_LEVEL_VIP , 
			'#proxy-z-template' , 
			'#proxy-data' , 
			15
		);
	});
	//添加会员
	$('#proxy-vip-add').click(function (){
		location.href = window.frontPath+ 'home#proxy/vip/add';
	});

	$.validation.init([{				//用户名校验
		ele : '[name="loginName"]',
		checkHandler : function (){
			if($.check.isUserN(this.ele.val())){
				return true;
			}else{
				return ADD_VIP_ERROR.LOGIN_NAME.ERROR;
			}
		}
	},{									//密码校验
		ele : '[name="userPassword"]',
		checkHandler : function (){
			var _val = $.trim(this.ele.val());
			if(_val == ''){
				return ADD_VIP_ERROR.USER_PWD.NULL;
			}
			if(!$.check.isPwd(_val)){
				return ADD_VIP_ERROR.USER_PWD.ERROR;
			}
			return true;
		}
	},{									//确认密码校验
		ele : '#confrimPwd',
		checkHandler : function (){
			var _val = $.trim(this.ele.val());
			var _pwd = $.trim($('#add-vip-form [name="userPassword"]').val());
			if(_val == ''){
				return ADD_VIP_ERROR.CONF_PWD.NULL;
			}
			if(_val !== _pwd){
				return ADD_VIP_ERROR.CONF_PWD.ERROR;
			}
			return true;
		}
	},
	{									//QQ校验
		ele : '[name="userQq"]',
		checkHandler : function (){
			var _val = $.trim(this.ele.val());
			if(!$.check.isQQ(_val)){
				return ADD_VIP_ERROR.QQ.ERROR;
			}
			return true;
		}
	},
	{									//用户姓名校验
		ele : '[name="userName"]',
		checkHandler : function (){
			var _val = $.trim(this.ele.val());
			if(_val === ''){
				return ADD_VIP_ERROR.USER_NAME.NULL;
			}
			/*if(!$.check.isUserZN(_val)){
				return ADD_VIP_ERROR.USER_NAME.ERROR;
			}*/
			return true;
		}
	},
	{									//返点校验
		ele : '[name="fandian"]',
		checkHandler : function (){
			var _val = $.trim(this.ele.val());
			var _maxFandian = parseFloat($('[data-id="fandian"]').html());
			if(/^\d+((\.\d+)|)$/.test(_val) && (parseFloat(_val) <= _maxFandian && parseFloat(_val) >= 0) ){
				return true;
			}else{
				return $.substitute(ADD_VIP_ERROR.FANDIAN.ERROR , {maxFandian : _maxFandian});
			}
		}
	}],$('#add-vip-form'));

	//添加会员  点击事件
	$('#add-vip').click(function (){
		if($.validation.isSuccess($('#add-vip-form'))){
			$.ajax({ 
			    url: CGI.PROXY_ADD_VIP, 
			    type: 'POST', 
			    dataType: 'json', 
			    data 	: $('#add-vip-form').serialize(),
			    contentType: 'application/x-www-form-urlencoded',
			    success: function(data) {
			    	if(0 === data.retcode){
			    		$.alert({
				    		status : 'ok',
							basicTitle : '增加成员成功！'
						});
			    		window.setTimeout(function (){
			    			$.none_alert(function (){
			    				window.location.href = window.frontPath+ 'home#proxy/vip';
			    			});
			    		},2000);
			    	}else{
			    		 $.alert({
    				    		status : 'error',
    							basicTitle : data.retmsg
    						});
			    	}
			    }
			});
		}
	});
	/**
	 * 获取当前会员信息
	 * @param  {[type]} _successCallBack [description]
	 * @return {[type]}                  [description]
	 */
	var getCurrentVipInfo = function (_jQ,_successCallBack){
		$.ajax({ 
		    url: CGI.CUR_PROXY_INFO(), 
		    data 	: 'uid='+_jQ.parents('tr').attr('data-uid'),
		    success: function (data){
		    	if(0 === data.retcode){
		    		_successCallBack && _successCallBack(data);
		    	}else{
		    		$.exception(data.retcode , data.retmsg);
		    	}
		    }
		});
	};

	//充值
	$('#proxy-data').delegate('[data-charge-user]','click',function (){
		getCurrentVipInfo($(this),function (data){
			$.alert({
				isIcon : false,
				width : 400,
				isTable : true,
				title  : '给下级充值',
				bigContents : [_.template($('#charge-table-template').html() , data.data)],
				buttons : [{flag:'chongzhi' , name : '充值' , handler : function (){
					var password =$("#proxy-coin-password").val();
					if(jQuery.trim(password)=="")
					{
						alert('请输入的资金密码。');
						return;
					}
					var _proxy_charge_val = $('#proxy-charge-inp').val();
					if(!$.check.isMoney(_proxy_charge_val)){
						alert('您输入的金额格式不对。');
						return;
					}
					
					var _dataTemplate = 'id={id}&userType={userType}&fandian={fandian}&coin={coin}&password={password}';
					var _data = $.substitute(_dataTemplate , {
                    	   id : data.data.id,
                    	   userName : data.data.username,
                    	   userType : data.data.userType,
                    	   fandian	: data.data.fanDian,
                    	   coin : _proxy_charge_val,
                    	   password:password
                    });
					 
					//给下级会员充值
					$.ajax({ 
					    url: CGI.CHARGE_SUB_PROXY(), 
					    data 	: _data,
					    success: function (data){
					    	if(0 === data.retcode){
					    		$.none_alert(function()
					    				{
					    			     $.alert({
							    		   status : 'ok',
										   basicTitle : '充值成功！'
									      }); 	
				    				      $('#proxy-vip-search').click();
				    				      reloadUserInfo();
					    				}
					    		);
					    	}else{
					    		$.exception(data.retcode , data.retmsg);
					    	}
					    }
					});
				}},{flag:'cancel' , name : '关闭' , handler : function (){
					$.none_alert();
				}}]
			});
		});
	});
	//修改
	$('#proxy-data').delegate('[data-modify-user]','click',function (){
		getCurrentVipInfo($(this),function (data){
    		$.alert({
    			isIcon		: false,
    			isTable		: true,
    			title		: '修改用户',
                bigContents : [_.template($('#update-user-template').html() , data.data)],
                buttons   : [
                    {flag : 'ok' , name : '确定' , handler : function (){
                       var _dataTemplate = 'id={id}&userType={userType}&fandian={fandian}';
                       var _data = $.substitute(_dataTemplate , {
                    	   id : $('#update_user_table [name="id"]').val(),
                    	   userType : $('#update_user_table [name="userType"]:checked').val(),
                    	   fandian	: ((+$('#update_user_table [name="fandian"]').val()) / 100)
                       });
                       $.ajax({
                    	   url : CGI.UPDATE_SUB_VIP(),
                    	   data : _data,
                    	   success : function (data){
                    		   if(0 === data.retcode){
                    			   $.none_alert(function (){
                    				   $.alert({
		           				    		status : 'ok',
		           							basicTitle : '修改成员成功！'
		           						});
                    				   window.P(
                    						window.Pager.currPage,
                    						'#proxy-search-form' , 
                    						 CGI.PROXY_PAGING , 
                    						'#proxy-z-template' , 
                    						'#proxy-data' , 
                    						15
                    					);
                    				   window.setTimeout(function (){
                    					   $.none_alert();
		                    		   },1000);
                    			   });
                    		   }else{
                    			   $.alert({
	           				    		status : 'error',
	           							basicTitle : data.retmsg
	           						});
                    		   }
                    	   }
                       });
                       return false;
                    }},{flag : 'cancel' , name : '关闭' , handler : function (){
                       $.none_alert();
                       return false;
                    }}
                ]
    	     });
    		
    		 
		});
	});
	
	jQuery(function()
			{ 
		       var minRebate =parseFloat(jQuery("#fandianSelect").attr("minRebate"));
		       var maxRebate=parseFloat(jQuery("#fandianSelect").attr("maxRebate"));
		       var dc = parseFloat(jQuery("#fandianSelect").attr("dc"));
		       for(var i=maxRebate;i>=minRebate-dc;i-=dc)
		       {
		    	    jQuery("<option value='"+Math.abs(i*100).toFixed(1)+"'>"+Math.abs(i*100).toFixed(1)+"%</option>").appendTo("#fandianSelect");
		       }
			});
	
})(window);